#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : 碰壁小球.py
@Author  : 神秘藏宝室
@Time    : 2020/2/14 18:55
店铺     : https://ilovemcu.taobao.com
"""
'''
第一次装pygame不支持自动补全代码，网上查询重装就可以了。
pip install pygame -i https://pypi.tuna.tsinghua.edu.cn/simple/
'''

# pygame最小环境
import sys, pygame

# 初始化
pygame.init()

speed = [2, 2]
BLACK = 0, 0, 0
# vInfo = pygame.display.Info()
# size = width, height = vInfo.current_w, vInfo.current_h
size = width, height = 600, 400
screen = pygame.display.set_mode(size, pygame.RESIZABLE)
pygame.display.set_caption('碰壁小球游戏')
# 设置图标
icon = pygame.image.load("title.png")
pygame.display.set_icon(icon)
# 定义小球
ball = pygame.image.load("ball.png")
# 获得覆盖球的方形对象
ballrect = ball.get_rect()

# fps
fps = 300  # 定义fps
fclock = pygame.time.Clock()

bgColor = pygame.Color('black')


def RGBChannel(a):
    return 0 if a < 0 else (255 if a > 255 else int(a))


# 循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("L", speed)
                speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1) * int(speed[0] / abs(speed[0]))
            if event.key == pygame.K_RIGHT:
                print("R", speed)
                speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1
            if event.key == pygame.K_UP:
                print("U", speed)
                speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1) * int(speed[1] / abs(speed[1]))
            if event.key == pygame.K_DOWN:
                print("D", speed)
                speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1
        elif event.type == pygame.VIDEORESIZE:  # 重新修正屏幕尺寸
            size = width, height = event.size[0], event.size[1]
            screen = pygame.display.set_mode(size, pygame.RESIZABLE)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # pos是位置，button是1是左键，3是右键
            print(event.pos, event.button)

    if pygame.display.get_active():
        ballrect = ballrect.move(speed[0], speed[1])
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    bgColor.r = RGBChannel(ballrect.left * 255 / width)
    bgColor.g = RGBChannel(ballrect.top * 255 / height)
    bgColor.b = RGBChannel(min(speed[0], speed[1]) * 255 / max(speed[0], speed[1], 1))
    screen.fill(bgColor)
    screen.blit(ball, ballrect)

    pygame.display.update()
    fclock.tick(fps)
